package com.cxp.utils;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import java.io.IOException;

/**
 * Created by cunxp on 2018/5/22.
 */
public class HttpGetProxy {

    private static final String PROXY_HOST = "127.0.0.1";
    private static final int PROXY_PORT = 1080;

    public static String getResponse(String url){
        String response = null;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(PROXY_HOST, PROXY_PORT);
        String username = "";
        String password = "";
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);
        client.getState().setProxyCredentials(authScope, credentials);
        try {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                byte[] responseBytes = method.getResponseBody();
                response = new String(responseBytes,"utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return response;
    }
}
